package org.jeecg.modules.sggg.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.sggg.entity.SgBlutdruckRecord;
import org.jeecg.modules.sggg.entity.SgDeviceRelevance;
import org.jeecg.modules.sggg.entity.SgGlucoseRecord;
import org.jeecg.modules.sggg.entity.SgMember;
import org.jeecg.modules.sggg.service.ISgMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.TimeZone;

@Api(tags = "掌护测量数据管理")
@RestController
@RequestMapping("/aicare/measure")
@Slf4j
public class SgAicareController {

    @Autowired
    private SgDeviceRelevanceController sgDeviceRelevanceController;

    @Autowired
    private SgBlutdruckRecordController sgBlutdruckRecordController;

    @Autowired
    private SgGlucoseRecordController sgGlucoseRecordController;

    @Autowired
    private ISgMemberService sgMemberService;

    @PostMapping(value = "/receiveDataForAicare", consumes = MediaType.TEXT_PLAIN_VALUE)
    public String receiveDataForAicare(@RequestBody String data) throws Exception {
        log.info("<----------掌护测量数据接收---------->");
        JSONObject jsonObject = JSONObject.parseObject(data);
        log.info("接收的数据：" + jsonObject.toJSONString());
        JSONObject contentObject = jsonObject.getJSONArray("content").getJSONObject(0);
        SgDeviceRelevance sgDeviceRelevance = sgDeviceRelevanceController.querySerialNumber(contentObject.getString("deviceImei")).getResult();
        // 是否有居民绑定该设备
        if (sgDeviceRelevance != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SgMember m = sgMemberService.getById(sgDeviceRelevance.getMemberId());
            if (jsonObject.getString("msgType").contains("bloodPressure")) {
                SgBlutdruckRecord sgBlutdruckRecord = new SgBlutdruckRecord();
                sgBlutdruckRecord.setMemberId(sgDeviceRelevance.getMemberId()); // 测量人id
                sgBlutdruckRecord.setSysOrgCode(m.getSysOrgCode()); // 测量人所属机构
                sgBlutdruckRecord.setDeviceId(contentObject.getString("deviceImei")); // 血压计设备唯一编码
                sgBlutdruckRecord.setSbpval(Double.valueOf(contentObject.getString("sbp"))); // 收缩压
                sgBlutdruckRecord.setDbpval(Double.valueOf(contentObject.getString("dbp"))); // 舒张压
                sgBlutdruckRecord.setHeartRate(Integer.valueOf(contentObject.getString("hr"))); // 心率
                Date date = dateFormat.parse(contentObject.getString("createTime"));
                sgBlutdruckRecord.setMeasuringTime(date); // 测量时间
                sgBlutdruckRecordController.add(sgBlutdruckRecord);
            } else {
                SgGlucoseRecord sgGlucoseRecord = new SgGlucoseRecord();
                sgGlucoseRecord.setMemberId(sgDeviceRelevance.getMemberId());
                sgGlucoseRecord.setSysOrgCode(m.getSysOrgCode());
                sgGlucoseRecord.setDeviceId(contentObject.getString("deviceImei"));
                sgGlucoseRecord.setGluval(Double.valueOf(contentObject.getString("sugar")));
                Date date = dateFormat.parse(contentObject.getString("createTime"));
                sgGlucoseRecord.setMeasuringTime(date);
                sgGlucoseRecord.setPhase(Integer.valueOf(contentObject.getString("timeType")));
                sgGlucoseRecordController.add(sgGlucoseRecord);
            }
        }
        return "success";
    }

    /**
     * 数据推送激活
     */
    @GetMapping("/notifyActive")
    public void notifyActive() {
        String baseUrl = "business.aicares.net/api";
        String method = "/organ/notifyActive";
        String access_id = "ac4c7d8ffe354e449d697f688835ee71";
        String access_key = "a8869c7cc5034d3d9c0101a0561d6651";

        // 获取当前时间
        Date currentDate = new Date();

        // 使用 SimpleDateFormat 和 TimeZone 来格式化日期时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        String dateTimeString = sdf.format(currentDate);

        // 签名生成
        String[] arr = {method, access_key, dateTimeString};
        Arrays.sort(arr);
        StringBuilder sb = new StringBuilder();
        for (String str : arr) {
            sb.append(str);
        }
        String signature = md5Str(sb.toString()).toUpperCase();

        // 构建 URL
        String url = baseUrl + "?method=" + method + "&access_id=" + access_id + "&timestamp=" + dateTimeString + "&signature=" + signature + "&format=json" + "&v=1.0.0";

        // 发送 HTTP POST 请求
        String response = HttpUtil.createPost(url).execute().body();

        log.info("掌护数据推送激活结果：" + response);
    }

    /**
     * 验证数据来自掌护云开放平台
     *
     * @param signature 签名
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     * @return String
     */
    @GetMapping("/receiveDataForAicare")
    public String validateData(String signature, String timestamp, String nonce, String echostr) {
        log.info("<----------掌护云数据验证---------->");
        String[] arr = {"EOBB6E6D9FF949BB875E65C449C13A85", timestamp, nonce};
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();
        for (String s : arr) {
            content.append(s);
        }

        String signature_ = md5Str(content.toString()).toUpperCase();

        if (signature.equals(signature_)) {
            log.info("原签名：" + signature + "， 本次生成的签名：" + signature_);
        }
        return echostr;
    }

    /**
     * md5对字符串进行加密
     *
     * @param str 要加密的字符串
     * @return String
     */
    public static String md5Str(String str) {
        MessageDigest md5 = null;
        String encryptedSing = "";
        try {
            md5 = MessageDigest.getInstance("MD5");
            md5.update(str.getBytes());
            byte[] digest = md5.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            encryptedSing = sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return encryptedSing;
    }
}
